package com.ljc.cjgl.service;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.ljc.cjgl.entitiy.Marking;
import com.ljc.cjgl.form.MarkingForm;
import com.ljc.cjgl.repository.MarkingResitory;

@Service
public class MarkingService {
	@Autowired
	private MarkingResitory markingDAO;
	
	
	public Marking findById(Integer id) {
		Optional<Marking> optional = markingDAO.findById(id);
		if(optional.isPresent()) {
			return optional.get();
		}
		return null;
	}
	
	public List<Marking> findAll(){
		return markingDAO.findAll();
	}
	
	public Page<Marking> findAll(Specification<Marking> specification,Pageable pageable){
		return markingDAO.findAll(specification, pageable);
	}
	
	public List<Marking> findByTestId(Integer id){
		return markingDAO.findByTestId(id);
	}
	
	public List<Marking> findByTestStatusLessThen(Integer n){
		return markingDAO.findByTestStatusLessThan(n);
	}

	public synchronized void save(MarkingForm form) {
		Marking model=new Marking();
		if(form.getId()!=null) {
			model=findById(form.getId());
		}
		BeanUtils.copyProperties(form, model,"id");
		markingDAO.save(model);
	}


	public synchronized boolean delete(List<Marking> markings) {
		try {
			for (Marking marking : markings) {
				if(marking.getId()!=null) {
					markingDAO.deleteById(marking.getId());
				}
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public List<Marking> findByTeacherId(Integer teacherId) {
		return markingDAO.findByTeacherId(teacherId);
		
	}
	
	
}
